package Pre.Work;

import java.util.Vector;

public class Exam02 {
    //创建⼀个Vector集合，⽤于存储⼀组商品的价格。编写⼀个函数，计算并返回所有商品价格的平均值。
    private String foodname;

    private double price;

    private int count;

    public Exam02(String foodname , double price, int count) {
        this.foodname = foodname;
        this.price = price;
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getFoodname() {
        return foodname;
    }

    public void setFoodname(String foodname) {
        this.foodname = foodname;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Exam02{" +
                "商品：'" + foodname + '\'' +
                ", 价格：" + price +
                ", 数量：" + count +
                '}';
    }
}

class Test{
    public static void main(String[] args) {
        Vector vector = new Vector();
        vector.add(new Exam02("苹果",5.5,5));
        vector.add(new Exam02("香蕉",6.8,6));
        vector.add(new Exam02("李子",8.8,8));
        vector.add(new Exam02("西瓜",1.5,12));
        vector.add(new Exam02("桃子",6.6,4));
        System.out.println("商品的平均价格为：" + Avg(vector));
    }

    public static double Avg(Vector vector){
        if (vector.isEmpty()){
            return -1;
        }
        double sum = 0;
        int count = 0;
        for (int i = 0; i < vector.size() ; i++) {
            Exam02 food =  (Exam02)vector.get(i);
            count += food.getCount();
            sum += (food.getPrice() * food.getCount());
        }
        return sum / count;
    }
}